package cn.tedu.mall.seckill.timer.job;

import cn.tedu.mall.seckill.mapper.SeckillSpuMapper;
import cn.tedu.mall.seckill.utils.RedisBloomUtils;
import cn.tedu.mall.seckill.utils.SeckillCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
@Slf4j
public class SeckillBloomInintialJob implements Job {

    @Autowired
    private RedisBloomUtils redisBloomUtils;

    @Autowired
    private SeckillSpuMapper seckillSpuMapper;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //首先确定保存布隆过滤器的秒杀批次的key
        //避免两个批次之间空窗期，而且也允许用户看到下一个批次的数据，会设计添加两个秒杀批次的布隆过滤器
        String bloomTodayKey = SeckillCacheUtils.getBloomFilterKey(LocalDate.now());
        String bloomTomorrowKey = SeckillCacheUtils.getBloomFilterKey(LocalDate.now().plusDays(1));
        //获取spuId的数组
        Long[] spuIds = seckillSpuMapper.findAllSeckillSpuIds();
        //布隆过滤器是支持使用String数组
        //需要转换数据类型，将long[] 转换成String[]
        String[] strIds=new String[spuIds.length];
        for (int i = 0; i < spuIds.length; i++) {
            strIds[i]=spuIds[i]+"";
        }
        //将String ids 添加到布隆过滤器中,我们准备了两个批次，实际上两个批次的数组是不一样的
        redisBloomUtils.bfmadd(bloomTodayKey,strIds);
        redisBloomUtils.bfmadd(bloomTomorrowKey,strIds);
        log.info("布隆过滤器加载完成");
    }
}
